package handler

import (
	"awesomeProject/app/model"
	"awesomeProject/app/request"
	"awesomeProject/app/response"
	"awesomeProject/app/service"
	"awesomeProject/app/verify"
	"awesomeProject/util"
	//"awesomeProject/global"
	"github.com/gin-gonic/gin"
	"strconv"
)

type CompanyHandler struct{}

var (
	companySrv service.CompanySrv
)

func (r *CompanyHandler) Pagination(ctx *gin.Context) {
	var req request.CompanyPagination
	_ = ctx.Bind(&req)
	// 表单验证
	if err := verify.CompanyPagination(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}

	response.Result(ctx, companySrv.Pagination(req))
	return
}

func (r *CompanyHandler) CompanyMap(ctx *gin.Context) {
	user, _ := ctx.Get("user")
	companyId := uint(0)
	companyIds := []uint{}
	if !user.(model.User).SuperAdmin {
		companyId = user.(model.User).CompanyId
		companyIds = util.GetUserCompanyIds(user.(model.User))
		if len(companyIds) > 0 {
			//global.LoggerOut(companyIds)
		} else {
			companyIds = append(companyIds, uint(companyId))
		}
	}
	response.Result(ctx, companySrv.All(companyIds, user.(model.User)))
	return
}

func (r *CompanyHandler) Create(ctx *gin.Context) {
	var req request.CompanyCreate
	_ = ctx.Bind(&req)
	// 表单校验
	if err := verify.CompanyCreate(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}
	fillAble := model.CompanyFillAble{
		CompanyName: req.CompanyName,
	}

	response.Result(ctx, companySrv.Create(fillAble))
	return
}

func (r CompanyHandler) Show(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	err, Company := companySrv.FindByID(uint(id))
	if err != nil {
		response.Result(ctx, response.ErrQuery.SetMsg(err.Error()))
	}
	response.Result(ctx, response.OK.WithData(Company))
	return
}

func (r *CompanyHandler) Update(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	var req request.CompanyUpdate
	_ = ctx.ShouldBindJSON(&req)
	if err := verify.CompanyUpdate(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}
	response.Result(ctx, companySrv.Update(uint(id), req))
	return
}

func (r *CompanyHandler) Del(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	response.Result(ctx, companySrv.Del(uint(id)))
	return
}
